﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using MINERP.DAL.GroupMember;
using MINERP.COM;
using MINERP.DAL;
using MINERP.DAL.CommonDAL;

using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.IO;
using MINERP.MODEL.GroupMember;
using MINERP.MODEL.FoundationModel;
using System.Transactions;
using MINERP.BLL.DigitalOutput;
using MINERP.BLL.Common;
using MINERP.MODEL.InfoConfig;

namespace MINERP.BLL.GroupMember
{
    public class GroupMemberBLL
    {
        private GroupMemberDAL _dal;
        private PaperFaceDAL _paperfaceDal;
        private PaperTypeDAL _paperTypeDal;
        private string _CurrentDirPath;
        private WorkFlowListBLL _workFlowBll;




        public GroupMemberBLL()
        {
            _dal = new GroupMemberDAL();
            _paperfaceDal = new PaperFaceDAL();
            _paperTypeDal = new PaperTypeDAL();
            _workFlowBll = new WorkFlowListBLL();
        }

        /// <summary>
        /// 得到组员的任务列表
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public DataTable GetTask(int userId, out int picCount, out double picAreaCount)
        {
            DataTable dtResult = null;
            picCount = 0;
            picAreaCount = 0;

            if (userId != 0)
            {
                List<WorkOrderFlowList> result;

                List<int> statusList = new List<int>();
                statusList.Add((int)OrderFlowListStatus.Complete);
                statusList.Add((int)OrderFlowListStatus.Error);
                statusList.Add((int)OrderFlowListStatus.UnProduct);
                using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
                {
                    result = DataEntites.WorkOrderFlowList.Where(wl => wl.UserId == userId).ToList().Where(wlf => !statusList.Contains(wlf.Status)).ToList();
                    if (result.Count > 0)
                    {
                        dtResult = ChangeTableFromItem(result, out  picCount, out picAreaCount);
                    }
                    else
                    {
                        dtResult = BLLHelper.CreateMemberTaskDT();
                    }
                }
            }

            return dtResult;
        }

        public List<TaskInfo> GetListTask(int userId, out int picCount, out double picAreaCount)
        {
            picCount = 0;
            picAreaCount = 0;
            List<TaskInfo> taskList = new List<TaskInfo>();
            if (userId != 0)
            {
                List<WorkOrderFlowList> result;

                List<int> statusList = new List<int>();
                statusList.Add((int)OrderFlowListStatus.Complete);
                statusList.Add((int)OrderFlowListStatus.Error);
                statusList.Add((int)OrderFlowListStatus.UnProduct);
                using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
                {
                    result = DataEntites.WorkOrderFlowList.Where(wl => wl.UserId == userId).ToList().Where(wlf => !statusList.Contains(wlf.Status)).ToList();
                    foreach (var wofl in result)
                    {
                        #region 数据加载
                        if (!wofl.orderInfoReference.IsLoaded)
                        {
                            wofl.orderInfoReference.Load();
                        }

                        if (wofl.orderInfo.status != (int)OrderInfoStatus.Doing)
                        {
                            continue;
                        }

                        if (!wofl.orderInfo.Tb_OrderBagReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_OrderBagReference.Load();
                        }
                        if (!wofl.orderInfo.Tb_ProductReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_ProductReference.Load();
                        }
                        if (!wofl.orderInfo.Tb_OrderBag.ShopReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_OrderBag.ShopReference.Load();
                        }
                        if (!wofl.tb_TechReference.IsLoaded)
                        {
                            wofl.tb_TechReference.Load();
                        }
                        if (!wofl.orderInfo.photoInfo.IsLoaded)
                        {
                            wofl.orderInfo.photoInfo.Load();
                        }
                       
                        #endregion

                        TaskInfo ti = new TaskInfo()
                        {
                            OrderProductId = wofl.orderInfo.OrderProductId,
                            CtmName = wofl.orderInfo.CtmName,
                            OrderProductName = wofl.orderInfo.OrderProductName,
                            ProductNum = wofl.orderInfo.productNum,
                            Priority = (int)wofl.orderInfo.Priority,
                            ShopName = wofl.orderInfo.Tb_OrderBag.Shop.shopName,
                            ShopId = wofl.orderInfo.Tb_OrderBag.Shop.ShopId,
                            status = wofl.Status,
                            PageNum = wofl.orderInfo.photoInfo.Count,
                            ProductName = wofl.orderInfo.Tb_Product.ProductName,
                            ProductSize = wofl.orderInfo.Tb_Product.Width.ToString() + "*" + wofl.orderInfo.Tb_Product.Height.ToString(),
                            ProductRemark = wofl.orderInfo.Remark,
                            TechId = wofl.tb_Tech.TechId,
                            TechName = wofl.tb_Tech.TechName,
                            IsDeisgnTech = wofl.tb_Tech.IsDesign,
                            IsRebackOrder = false,
                            OrderPath=wofl.orderInfo.OrderPath,
                            
                        };

                        if (wofl.orderInfo.photoInfo.FirstOrDefault() != null)//产品有照片
                        {
                            if (!wofl.orderInfo.photoInfo.First().paperFaceReference.IsLoaded)
                            {
                                wofl.orderInfo.photoInfo.First().paperFaceReference.Load();
                            }
                            if (!wofl.orderInfo.photoInfo.First().paperTypeReference.IsLoaded)
                            {
                                wofl.orderInfo.photoInfo.First().paperTypeReference.Load();
                            }
                            ti.PaperFaceName = wofl.orderInfo.photoInfo.First().paperFace.Name;
                            ti.PaperTypeName = wofl.orderInfo.photoInfo.First().paperType.Name;
                            int printerId = (int)wofl.orderInfo.photoInfo.First().printerId;
                            printer printer = DataEntites.printer.FirstOrDefault(p => p.PrinterID == printerId);
                            if (printer != null)
                            {
                                ti.PrinterName = printer.PName;
                            }
                            else
                            {
                                ti.PrinterName = "";
                            }
                        }
                        else
                        {
                            ti.PaperFaceName = "";
                            ti.PaperTypeName = "";
                            ti.PrinterName = "";
                        }
                        ti.PhotoList = new List<PhotoInfo_GM>();
                        List<photoInfo> Plist = wofl.orderInfo.photoInfo.ToList();
                        foreach (var p in Plist)
                        {
                            if (!p.paperTypeReference.IsLoaded)
                            {
                                p.paperTypeReference.Load();
                            }
                            if (!p.paperFaceReference.IsLoaded)
                            {
                                p.paperFaceReference.Load();
                            }

                            PhotoInfo_GM pgm = new PhotoInfo_GM()
                            {
                                Height = p.Height,
                                IsEdit = false,
                                PicPath = p.picPath,
                                PhotoName = p.photoName,
                                Width = p.Width,
                                PhotoBarCode = p.PhotoBarCode,
                                PhotoId = p.photoId,
                                Remark = p.Remark,
                                OldPicPath = p.OldPicPath,
                                IsRebackPhoto = (p.status2 == (int)PhotoStatus2.innerReturn) ? true : false,
                                PaperFaceName = p.paperFace.Name,
                                PaperTypeName = p.paperType.Name
                            };
                            printer printer = DataEntites.printer.FirstOrDefault(pr => pr.PrinterID == p.printerId);
                            if (printer != null)
                            {
                                pgm.PrinterName = printer.PName;
                            }
                            else
                            {
                                pgm.PrinterName = "";
                            }
                            //if (pgm.IsRebackPhoto)
                            //{
                            //    ti.IsRebackOrder = true;
                            //}
                            ti.PhotoList.Add(pgm);
                            picAreaCount += p.Width * p.Height;
                            picCount++;
                        }
                        ti.PhotoList = ti.PhotoList.OrderByDescending(p => p.IsRebackPhoto).ToList();//返单的照片在前面

                        //if (ti.IsRebackOrder)
                        //{
                        //    ti.PhotoList = ti.PhotoList.Where(p => p.IsRebackPhoto).ToList();
                        //    ti.Priority = 12;//返单的加急级别最高
                        //}

                        taskList.Add(ti);
                    }
                }
            }
            picAreaCount = picAreaCount * 2.54 * 2.54 / 10000;
            taskList = taskList.OrderByDescending(t => t.OrderProductId).ToList();
            return taskList;
        }


        /// <summary>
        /// 得到默认当天完成的任务
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="picCount"></param>
        /// <param name="picAreaCount"></param>
        /// <returns></returns>
        public DataTable GetOveredTask(int userId, out int picCount, out double picAreaCount)
        {

            //默认取当天的
            return GetHistoryFilter(userId, DateTime.Now.Date, DateTime.Now.Date.AddDays(1), out picCount, out picAreaCount);
        }

        #region 暂时没有使用
        //private DataTable GetBaseTask(int userId, OrderFlowListStatus status1, OrderFlowListStatus status2, out int picCount, out double picAreaCount)
        //{
        //    picAreaCount = 0;
        //    picCount = 0;
        //    DataTable dtResult = null;
        //    using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
        //    {
        //        string strESQL = string.Format("it.userid={0} and it.status in {1}", userId, "{" + Convert.ToInt32(status1) + "," + Convert.ToInt32(status2)) + "}";
        //        List<WorkOrderFlowList> wflList = DataEntites.WorkOrderFlowList.Where(strESQL).ToList();
        //        dtResult = ChangeTableFromItem(wflList, out picCount, out picAreaCount);
        //    }
        //    return dtResult;
        //}
        #endregion



        /// <summary>
        /// 员工查看自己的某一时期内的任务量
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="picCount">照片总数</param>
        /// <param name="picAreaCount">面积总数</param>
        /// <returns></returns>
        public DataTable GetHistoryFilter(int userId, DateTime startTime, DateTime endTime, out int picCount, out double picAreaCount)
        {
            picAreaCount = 0;
            picCount = 0;
            DataTable dtTaskTask = BLLHelper.CreateMemberTaskDT();
            int status = (int)OrderFlowListStatus.Complete;
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                List<WorkOrderFlowList> wflList = DataEntites.WorkOrderFlowList.Where(wf => wf.UserId == userId && wf.Status == status && wf.CompletedTime >= startTime && wf.CompletedTime <= endTime).ToList();
                foreach (var item in wflList)
                {
                    #region load data
                    if (!item.orderInfoReference.IsLoaded)
                    {
                        item.orderInfoReference.Load();
                    }
                    else
                    {
                        item.orderInfoReference.Load(MergeOption.OverwriteChanges);
                    }

                    if (!item.orderInfo.Tb_OrderBagReference.IsLoaded)
                    {
                        item.orderInfo.Tb_OrderBagReference.Load();
                    }
                    else
                    {
                        item.orderInfo.Tb_OrderBagReference.Load(MergeOption.OverwriteChanges);
                    }

                    if (!item.orderInfo.Tb_ProductReference.IsLoaded)
                    {
                        item.orderInfo.Tb_ProductReference.Load();
                    }
                    else
                    {
                        item.orderInfo.Tb_ProductReference.Load(MergeOption.OverwriteChanges);
                    }

                    if (!item.orderInfo.Tb_OrderBag.ShopReference.IsLoaded)
                    {
                        item.orderInfo.Tb_OrderBag.ShopReference.Load();
                    }
                    else
                    {
                        item.orderInfo.Tb_OrderBag.ShopReference.Load(MergeOption.OverwriteChanges);
                    }
                    if (!item.tb_TechReference.IsLoaded)
                    {
                        item.tb_TechReference.Load();
                    }
                    else
                    {
                        item.tb_TechReference.Load(MergeOption.OverwriteChanges);
                    }

                    if (!item.orderInfo.photoInfo.IsLoaded)
                    {
                        item.orderInfo.photoInfo.Load();
                    }
                    #endregion

                    foreach (var photo in item.orderInfo.photoInfo)
                    {
                        picAreaCount += photo.Width * photo.Height * 2.54 * 2.54 / 10000;
                    }
                    //picAreaCount *= item.orderInfo.productNum;//面积*份数

                    picCount += item.orderInfo.photoInfo.Count;

                    int OrderProductId = item.orderInfo.OrderProductId;
                    string orderName = item.orderInfo.Tb_OrderBag.BagName;
                    string productName = item.orderInfo.Tb_Product.ProductName;
                    string CtmName = item.orderInfo.CtmName;
                    DateTime orderTime = item.orderInfo.Tb_OrderBag.OrderTime;
                    DateTime fetchTime = item.orderInfo.Tb_OrderBag.FetchTime;
                    DateTime CompleteTime = (DateTime)item.CompletedTime;
                    int shopId = item.orderInfo.Tb_OrderBag.Shop.ShopId;
                    string strShopName = item.orderInfo.Tb_OrderBag.Shop.shopName;
                    int priority = item.orderInfo.Tb_OrderBag.Priority;
                    string orderPath = item.orderInfo.OrderPath;
                    int techId = item.tb_Tech.TechId;
                    string techName = item.tb_Tech.TechName;
                    bool techIsDesign = item.tb_Tech.IsDesign;
                    string remark = item.orderInfo.Remark;
                    string strStatus = "";
                    switch ((OrderFlowListStatus)item.Status)
                    {
                        case OrderFlowListStatus.Wait: strStatus = "等待";
                            break;
                        case OrderFlowListStatus.Useable: strStatus = "等待接收";
                            break;
                        case OrderFlowListStatus.UseableAccept: strStatus = "已接收";
                            break;
                        case OrderFlowListStatus.Error: strStatus = "错误";
                            break;
                        case OrderFlowListStatus.Complete: strStatus = "完成";
                            break;
                        case OrderFlowListStatus.Disable: strStatus = "不可用";
                            break;
                        case OrderFlowListStatus.UnProduct: strStatus = "暂停生产";
                            break;
                        default:
                            break;
                    }
                    dtTaskTask.Rows.Add(new object[] { OrderProductId, orderName, productName, item.orderInfo.Tb_Product.Width.ToString() + "*" + item.orderInfo.Tb_Product.Height.ToString(), item.orderInfo.productNum, item.orderInfo.PageNum, shopId, strShopName, CtmName, orderTime, fetchTime, priority, orderPath, techName, techId, techIsDesign, remark, strStatus, item.Status, CompleteTime });
                }
            }
            return dtTaskTask;
        }

        public DataTable GetHistoryFilter(int userId, DateTime startTime, DateTime endTime)
        {
            string sql = " SELECT     New_EmployeePerformance.OrderproductId, tb_Tech.TechName, New_EmployeePerformance.ShopName, New_EmployeePerformance.CtmName, " +
                       " New_EmployeePerformance.OrderProductName, CASE CHARINDEX('_', ORDERPRODUCTNAME) " +
                       " WHEN 0 THEN ORDERPRODUCTNAME ELSE (CASE OrderProductName WHEN ' ' THEN ' ' ELSE REVERSE(LEFT(REVERSE(New_EmployeePerformance.OrderProductName)," +
                       " CHARINDEX('_', REVERSE(New_EmployeePerformance.OrderProductName)) - 1)) END) END AS ProductName, CASE CHARINDEX('_', " +
                       " ORDERPRODUCTNAME) " +
                       " WHEN 0 THEN ORDERPRODUCTNAME ELSE (CASE OrderProductName WHEN ' ' THEN ' ' ELSE REVERSE(LEFT(REVERSE(New_EmployeePerformance.OrderProductName)," +
                       " CHARINDEX('_', REVERSE(New_EmployeePerformance.OrderProductName)) - 1)) END) END AS ProductName, " +
                      " New_EmployeePerformance.OrderCreateTime, New_EmployeePerformance.ReceivedTime, users.UserName, " +
                      " CASE Status WHEN 7 THEN '暂停' WHEN 12 THEN '已删除' WHEN 8 THEN '已完成 ' ELSE '正常生产' END AS StatusName, " +
                      " New_EmployeePerformance.PhotoTotalNum, New_EmployeePerformance.SinglePageNum, New_EmployeePerformance.MultiplePageNum, " +
                      " New_EmployeePerformance.OrderPath, New_EmployeePerformance.TechCompletedTime, New_EmployeePerformance.OrderConpletedTime, " +
                      " New_EmployeePerformance.PreOrderAreas, New_EmployeePerformance.OrderArea, New_EmployeePerformance.OrderCount, " +
                      " New_EmployeePerformance.ProductPhotoNum" +
" FROM         New_EmployeePerformance INNER JOIN" +
                      " tb_Tech ON New_EmployeePerformance.TechId = tb_Tech.TechId INNER JOIN" +
                      " users ON New_EmployeePerformance.UserId = users.userID" +
" WHERE     (New_EmployeePerformance.UserId ="+userId+") AND (New_EmployeePerformance.OrderCreateTime < '" + endTime.ToString("yyyy-MM-dd") + "') AND " +
                      " (New_EmployeePerformance.OrderCreateTime > '" + startTime.ToString("yyyy-MM-dd") + "')";

            return CommOperDB.ExceSQLDataTable(sql);
 
        }
        public DataTable GetHistoryFilterAll(int userId, DateTime startTime, DateTime endTime)
        {

            string sql = " SELECT     New_EmployeePerformance.OrderproductId, tb_Tech.TechName, New_EmployeePerformance.ShopName, New_EmployeePerformance.CtmName, " +
                       " New_EmployeePerformance.OrderProductName, CASE CHARINDEX('_', ORDERPRODUCTNAME) " +
                       " WHEN 0 THEN ORDERPRODUCTNAME ELSE (CASE OrderProductName WHEN ' ' THEN ' ' ELSE REVERSE(LEFT(REVERSE(New_EmployeePerformance.OrderProductName)," +
                       " CHARINDEX('_', REVERSE(New_EmployeePerformance.OrderProductName)) - 1)) END) END AS ProductName, CASE CHARINDEX('_', " +
                       " ORDERPRODUCTNAME) " +
                       " WHEN 0 THEN ORDERPRODUCTNAME ELSE (CASE OrderProductName WHEN ' ' THEN ' ' ELSE REVERSE(LEFT(REVERSE(New_EmployeePerformance.OrderProductName)," +
                       " CHARINDEX('_', REVERSE(New_EmployeePerformance.OrderProductName)) - 1)) END) END AS ProductName, " +
                      " New_EmployeePerformance.OrderCreateTime, New_EmployeePerformance.ReceivedTime, users.UserName, " +
                      " CASE Status WHEN 7 THEN '暂停' WHEN 12 THEN '已删除' WHEN 8 THEN '已完成 ' ELSE '正常生产' END AS StatusName, " +
                      " New_EmployeePerformance.PhotoTotalNum, New_EmployeePerformance.SinglePageNum, New_EmployeePerformance.MultiplePageNum, " +
                      " New_EmployeePerformance.OrderPath, New_EmployeePerformance.TechCompletedTime, New_EmployeePerformance.OrderConpletedTime, " +
                      " New_EmployeePerformance.PreOrderAreas, New_EmployeePerformance.OrderArea, New_EmployeePerformance.OrderCount, " +
                      " New_EmployeePerformance.ProductPhotoNum" +
" FROM         New_EmployeePerformance INNER JOIN" +
                      " tb_Tech ON New_EmployeePerformance.TechId = tb_Tech.TechId INNER JOIN" +
                      " users ON New_EmployeePerformance.UserId = users.userID" +
" WHERE     (New_EmployeePerformance.UserId in (select userid from users where GroupId = (select GroupId from users where userid=" + userId + " ) and IsUseful=1 )) AND (New_EmployeePerformance.OrderCreateTime < '" + endTime.ToString("yyyy-MM-dd") + "') AND " +
                      " (New_EmployeePerformance.OrderCreateTime > '" + startTime.ToString("yyyy-MM-dd") + "')";

            return CommOperDB.ExceSQLDataTable(sql);

        }
        /// <summary>
        /// 得到某一产品定单所对应的照片信息
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public DataTable GetPhotoInfo(int orderProductId)
        {
            DigitalOutputBLL bll = new DigitalOutputBLL();
            DataTable dtSource = BLLHelper.CreatePhotoInfoDT();
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                foreach (var item in GetPhotosByOrderProductId(DataEntites, orderProductId))
                {
                    dtSource.Rows.Add(new object[] { item.photoId, item.PhotoBarCode, item.Width.ToString() + "*" + item.Height.ToString(), item.photoName, item.picPath, item.Remark, false, true });
                }
            }
            return dtSource;
        }

        /// <summary>
        /// 获取所有任务
        /// </summary>
        /// <returns></returns>
        public bool ReceiveAllTask(int userId)
        {
            return _dal.ReceiveAllTask(userId, OrderFlowListStatus.Useable, OrderFlowListStatus.UseableAccept);
        }

        /// <summary>
        /// 得到备份的图片的信息
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public DataTable GetBackUpPhotoInfo(int orderProductId)
        {
            DataTable dtSource = BLLHelper.CreatePhotoInfoDT();
            //string strPathDir = "";//要将原始图片拷贝到哪个目录下
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                orderInfo oi;
                oi = DataEntites.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductId);
                foreach (var item in oi.photoInfo)
                {
                    dtSource.Rows.Add(MovePic(item));
                }
                //移动新图片
            }

            return dtSource;
        }


        #region  //helpMethod

        private List<photoInfo> GetPhotosByOrderProductId(newSampleYPDBEntities context, int orderProductId)
        {
            object o = null;
            context.TryGetObjectByKey(new EntityKey("newSampleYPDBEntities.orderInfo", "OrderProductId", orderProductId), out o);
            orderInfo oi = (orderInfo)o;
            if (!oi.photoInfo.IsLoaded)
            {
                oi.photoInfo.Load();
            }
            return oi.photoInfo.ToList();
        }

        object[] MovePic(photoInfo movepi)
        {
            string strPathDir = "";//要将原始图片拷贝到哪个目录下
            if (strPathDir == "")
            {
                strPathDir = movepi.picPath.Substring(0, movepi.picPath.LastIndexOf(@"\"));
                _CurrentDirPath = strPathDir.Substring(0, strPathDir.LastIndexOf(@"\"));
            }
            //1000048337_014_1 (1).jpg原如图片名==1 (1).jpg
            string picName = movepi.picPath.Substring(movepi.picPath.LastIndexOf(@"\") + 1);
            string oldPicName = picName.Substring(15);//得到1 (1).jpg;
            string backPicPath = strPathDir + "\\Backup\\" + oldPicName;
            FileInfo fi;
            try
            {
                if (!File.Exists(backPicPath))
                    return new object[] { movepi.photoId, movepi.PhotoBarCode, movepi.Width.ToString() + "*" + movepi.Height.ToString(), movepi.photoName, movepi.picPath, "原图片不存在，无法还原" };

                fi = new FileInfo(backPicPath);
                //fi = new FileInfo(movepi.OldPicPath);
                fi.CopyTo(movepi.picPath, true);
                return new object[] { movepi.photoId, movepi.PhotoBarCode, movepi.Width.ToString() + "*" + movepi.Height.ToString(), movepi.photoName, movepi.picPath, movepi.Remark };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 改变状态 help method
        /// </summary>
        /// <param name="OrderProductId">orderinfo的ID</param>
        /// <param name="orderFlowListStatus">oldstatus</param>
        /// <param name="orderFlowListStatus_3">new status</param>
        private void ModifyStatus(int OrderProductId, OrderFlowListStatus originalStatus, OrderFlowListStatus newStatus)
        {
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                orderInfo oi = DataEntites.orderInfo.Where(o => o.OrderProductId == OrderProductId).First();
                if (!oi.WorkOrderFlowList.IsLoaded)
                {
                    oi.WorkOrderFlowList.Load();
                }
                WorkOrderFlowList wfl = oi.WorkOrderFlowList.Where(p => p.Status == (int)originalStatus).FirstOrDefault();

                if (wfl != null)
                {
                    wfl.Status = (int)newStatus;
                    wfl.ReceiveTime = CommonMethodDAL.GetServerTime();//获取系统时间
                    if (wfl.UserId != 0)
                    {
                        DataEntites.SaveChanges();
                    }
                }
            }
        }

        private DataTable ChangeTableFromItem(List<WorkOrderFlowList> wflList, out int picCount, out double picAreaCount)
        {
            picAreaCount = 0;
            picCount = 0;
            DataTable dtTaskTask = BLLHelper.CreateMemberTaskDT();
            foreach (WorkOrderFlowList item in wflList)
            {
                if (!item.orderInfoReference.IsLoaded)
                {
                    item.orderInfoReference.Load();
                }
                //item.orderInfoReference.Load(MergeOption.AppendOnly);
                if (!item.orderInfo.Tb_OrderBagReference.IsLoaded)
                {
                    item.orderInfo.Tb_OrderBagReference.Load();
                }
                //item.orderInfo.Tb_OrderBagReference.Load(MergeOption.AppendOnly);
                if (!item.orderInfo.Tb_ProductReference.IsLoaded)
                {
                    item.orderInfo.Tb_ProductReference.Load();
                }
                //item.orderInfo.Tb_ProductReference.Load(MergeOption.AppendOnly);
                if (!item.orderInfo.Tb_OrderBag.ShopReference.IsLoaded)
                {
                    item.orderInfo.Tb_OrderBag.ShopReference.Load();
                }
                //item.orderInfo.Tb_OrderBag.ShopReference.Load(MergeOption.AppendOnly);
                if (!item.tb_TechReference.IsLoaded)
                {
                    item.tb_TechReference.Load();
                }
                //item.tb_TechReference.Load(MergeOption.AppendOnly);


                if (!item.orderInfo.photoInfo.IsLoaded)
                {
                    item.orderInfo.photoInfo.Load();
                }
                foreach (var photo in item.orderInfo.photoInfo)
                {
                    picAreaCount += photo.Width * photo.Height * 2.54 * 2.54 / 10000;
                }

                //picAreaCount *= item.orderInfo.productNum;//面积*份数

                picCount += item.orderInfo.photoInfo.Count;

                int OrderProductId = item.orderInfo.OrderProductId;
                string orderName = item.orderInfo.Tb_OrderBag.BagName;
                string productName = item.orderInfo.Tb_Product.ProductName;
                string CtmName = item.orderInfo.CtmName;
                DateTime orderTime = item.orderInfo.Tb_OrderBag.OrderTime;
                DateTime fetchTime = item.orderInfo.Tb_OrderBag.FetchTime;
                DateTime CompleteTime = item.orderInfo.CompleteTime;
                int shopId = item.orderInfo.Tb_OrderBag.Shop.ShopId;
                string strShopName = item.orderInfo.Tb_OrderBag.Shop.shopName;
                int priority = (int)item.orderInfo.Priority;
                string orderPath = item.orderInfo.OrderPath;
                int techId = item.tb_Tech.TechId;
                string techName = item.tb_Tech.TechName;
                bool techIsDesign = item.tb_Tech.IsDesign;
                string remark = item.orderInfo.Remark;
                //string strStatus = (item.Status == Convert.ToInt32(OrderFlowListStatus.Useable)) ? "等待接收" : "已接受";
                string strStatus;
                switch (item.Status)
                {
                    case (int)OrderFlowListStatus.Wait: strStatus = "未到本岗位操作";
                        break;
                    case (int)OrderFlowListStatus.Useable: strStatus = "等待接收";
                        break;
                    case (int)OrderFlowListStatus.UseableAccept: strStatus = "已接受";
                        break;
                    case (int)OrderFlowListStatus.Complete: strStatus = "已完成";
                        break;
                    case (int)OrderFlowListStatus.Error: strStatus = "错误";
                        break;
                    case (int)OrderFlowListStatus.UnProduct: strStatus = "不可生产";
                        break;
                    default: strStatus = "未知状态";
                        break;
                }
                dtTaskTask.Rows.Add(new object[] { OrderProductId, orderName, productName, item.orderInfo.Tb_Product.Width.ToString() + "*" + item.orderInfo.Tb_Product.Height.ToString(), item.orderInfo.productNum, item.orderInfo.PageNum, shopId, strShopName, CtmName, orderTime, fetchTime, priority, orderPath, techName, techId, techIsDesign, remark, strStatus, item.Status, CompleteTime });
            }
            return dtTaskTask;
        }

        #endregion


        /// <summary>
        /// 部分替换
        /// </summary>
        /// <param name="orderProductId">定单产品ID</param>
        /// <param name="replacePhotoCode">要替换的照片barcode</param>
        /// <returns></returns>
        public DataTable GetPartsBackUpPhotoInfo(int orderProductId, List<string> replacePhotoCodeList)
        {
            DataTable dtSource = BLLHelper.CreatePhotoInfoDT();
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                foreach (var item in GetPhotosByOrderProductId(DataEntites, orderProductId))
                {
                    string barCode = replacePhotoCodeList.Find(delegate(string Replacecode)
                    {
                        if (item.PhotoBarCode == Replacecode)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    });
                    if (string.IsNullOrEmpty(barCode))//不需要替换的
                    {
                        dtSource.Rows.Add(new object[] { item.photoId, item.PhotoBarCode, item.Width.ToString() + "*" + item.Height.ToString(), item.photoName, item.picPath, item.Remark });
                    }
                    else//需要替换的
                    {
                        dtSource.Rows.Add(MovePic(item));
                    }
                }
            }
            return dtSource;
        }



        /// <summary>
        /// 完成（非设计类的定单的工作）
        /// </summary>
        /// <param name="p"></param>
        /// <returns>true:成功 false:失败</returns>
        public bool CompleteWork(int curTechId, int userid, int orderProductId,List<EPByPhotoSpecInfo> epByPhotoSpecInfoList,WorkShop_Info workshop)
        {
            //bool result = _dal.CompleteWork(orderProductId, OrderFlowListStatus.Complete, DateTime.Now, OrderFlowListStatus.UseableAccept);
            //return result;
            return _workFlowBll.OverCurTechForGroupMember(curTechId, userid, orderProductId,epByPhotoSpecInfoList,workshop);
        }

        /// <summary>
        /// 完成设计类的工作
        /// </summary>
        /// <param name="p"></param>
        /// <param name="_ImportPicList"></param>
        /// <returns></returns>
        ////public bool CompleteDesinedWork(int techId,int Uid,bool isRebackOrder,int orderProductId, List<BigPicInfo> _ImportPicList,bool isOriPicOver)
        //{
        //    try
        //    {
        //        if (!isOriPicOver)
        //        {
        //            using (TransactionScope trs = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 5, 0)))
        //            {
        //                try
        //                {
        //                    using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
        //                    {
        //                        //从photoInfo表中删除旧图片
        //                        paperFace oldPaperFace;
        //                        paperType oldPaperType;
        //                        GetOldFaceAndType(out oldPaperFace, out oldPaperType, orderProductId, DataEntites);
        //                        photoInfo oldPhotoInfo = _dal.DeletePhotoByOrderProductId(orderProductId, DataEntites);
        //                        string strPathDir = oldPhotoInfo.picPath.Substring(0, oldPhotoInfo.picPath.LastIndexOf(@"\"));
        //                        _CurrentDirPath = strPathDir.Substring(0, strPathDir.LastIndexOf(@"\"));
        //                        //移动图片
        //                        string newDirPath = _CurrentDirPath + "\\PSD\\";
        //                        if (!Directory.Exists(newDirPath))
        //                        {
        //                            Directory.CreateDirectory(newDirPath);
        //                        }
        //                        foreach (var item in _ImportPicList)
        //                        {
        //                            FileInfo fi = new FileInfo(item.PicPath);
        //                            fi.CopyTo(newDirPath + item.PicName, true);
        //                        }



        //                        List<photoInfo> newPigPhotoList = new List<photoInfo>();
        //                        foreach (var item in _ImportPicList)
        //                        {
        //                            photoInfo pi = new photoInfo();
        //                            pi.photoName = item.PicName;
        //                            pi.picPath = newDirPath + item.PicName;
        //                            pi.pixHeight = item.PixHeight;
        //                            pi.pixWidth = item.PixWidth;
        //                            pi.Remark = item.PicName;
        //                            pi.status = Convert.ToInt32(PhotoStatus.NoDistributePrinter);
        //                            pi.Width = item.Width;
        //                            pi.Height = item.Height;
        //                            pi.TotalNum = oldPhotoInfo.TotalNum;
        //                            pi.IsModifySize = oldPhotoInfo.IsModifySize;

        //                            pi.paperType = oldPaperType;
        //                            pi.paperFace = oldPaperFace;

        //                            pi.OldPicPath = " ";
        //                            pi.PhotoBarCode = " ";
        //                            pi.printerId = oldPhotoInfo.printerId;
        //                            newPigPhotoList.Add(pi);
        //                        }

        //                        //向数据表添加新图片的记录
        //                        //_dal.AddNewPic(_ImportPicList, oldPhotoInfo, orderProductId);
        //                        _dal.AddNewPic(newPigPhotoList, orderProductId, DataEntites);
        //                    }

        //                    //改变流程状态
        //                    //_dal.CompleteWork(orderProductId, OrderFlowListStatus.Complete, DateTime.Now, OrderFlowListStatus.UseableAccept);

        //                    trs.Complete();
        //                }
        //                catch(Exception ex)
        //                {
        //                    WriteLogForCheck.WriteLogFile("在进行设计提交时，旧照片删除，新照片添加时出错:" + ex.Message);
        //                    return false;
        //                };
        //            }


        //            return CompleteWork(techId, Uid, orderProductId, !isRebackOrder);
        //        }
        //        else//原片导入
        //        {
        //            return CompleteWork(techId, Uid, orderProductId, !isRebackOrder);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //        //return false;
        //    }
        //    return true;
        //}

        /// <summary>
        /// 得到此产品的照片的纸型、纸面
        /// </summary>
        /// <param name="oldPaperFace"></param>
        /// <param name="oldPaperType"></param>
        /// <param name="orderProductId"></param>
        private void GetOldFaceAndType(out paperFace oldPaperFace, out paperType oldPaperType, int orderProductId, newSampleYPDBEntities dataBase)
        {

            //using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            //{
            orderInfo oi = dataBase.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductId);
            if (!oi.photoInfo.IsLoaded)
            {
                oi.photoInfo.Load();
            }

            photoInfo pi = oi.photoInfo.FirstOrDefault();
            if (pi == null)
            {
                oldPaperFace = null;
                oldPaperType = null;
                return;
            }
            if (!pi.paperFaceReference.IsLoaded)
            {
                pi.paperFaceReference.Load();
            }

            oldPaperFace = pi.paperFace;
            if (!pi.paperTypeReference.IsLoaded)
            {
                pi.paperTypeReference.Load();
            }

            oldPaperType = pi.paperType;
            //}
        }

        /// <summary>
        /// 得到某一定单的需求（remark）
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public string GetRemarkByOrderProductId(int orderProductId)
        {
            string result = "";
            if (orderProductId >= 1)
            {

                //return _dal.GetRemarkByOrderProductId(orderProductId);
                using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
                {
                    orderInfo oi = dataBase.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductId);
                    if (oi != null)
                    {
                        if (!oi.Tb_OrderBagReference.IsLoaded)
                        {
                            oi.Tb_OrderBagReference.Load();
                        }

                        result = oi.Tb_OrderBag.Remark;
                    }
                }
            }

            return result;
        }

        public List<string> GetCtmList(int shopId)
        {
            List<string> listCtm = new List<string>();
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                List<Tb_OrderBag> orderBagList = DataEntites.Tb_OrderBag.Where(ob => ob.Shop.ShopId == shopId).ToList();
                foreach (var item in orderBagList)
                {
                    foreach (var oi in item.orderInfo)
                    {
                        string reslut = listCtm.Find(delegate(string ctm)
                        {
                            if (ctm == oi.CtmName)
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        });
                        if (string.IsNullOrEmpty(reslut))
                        {
                            listCtm.Add(oi.CtmName);
                        }
                    }
                }
            }

            return listCtm;
        }

        /// <summary>
        /// 接收某产品（页面上的双击操作，就报表接收）
        /// </summary>
        /// <param name="OrderProductId"></param>
        public void ReceiveSelectedTask(int OrderProductId)
        {
            ModifyStatus(OrderProductId, OrderFlowListStatus.Useable, OrderFlowListStatus.UseableAccept);
        }



        /// <summary>
        /// 得到此产品的组合产品的列表
        /// </summary>
        /// <returns>此产品如果不是组合产品，则返回NULL，如果是则返回LIST</returns>
        public List<Tb_Product_Info> GetComposeProducts(int OrderProductId)
        {
            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
            {
                orderInfo oi = DataEntites.orderInfo.FirstOrDefault(o => o.OrderProductId == OrderProductId);

                if (!oi.Tb_ProductReference.IsLoaded)
                {
                    oi.Tb_ProductReference.Load();
                }
                Tb_Product prouct = oi.Tb_Product;
                if (!prouct.Product_Compose_Relation.IsLoaded)
                {
                    prouct.Product_Compose_Relation.Load();
                }
                int count = prouct.Product_Compose_Relation.Count;
                if (count < 1)// 不是组合产品
                {
                    return null;
                }
                else
                {
                    List<Tb_Product_Info> listProduct = new List<Tb_Product_Info>();
                    foreach (var item in prouct.Product_Compose_Relation)
                    {
                        if (!item.Tb_Product1Reference.IsLoaded)
                        {
                            item.Tb_Product1Reference.Load();
                        }
                        listProduct.Add(new Tb_Product_Info() { PageNum = item.Tb_Product1.PageNum, ProductName = item.Tb_Product1.ProductName, ProductSize = item.Tb_Product1.Width.ToString() + "*" + item.Tb_Product1.Height.ToString() + "英寸" });
                    }

                    return listProduct;
                }
            }
        }



        public bool ReBackTask(TaskInfo taskInfo, out string msg)//退回任务
        {
            //1.修改workorderflowlist的userid=0
            //2.修改workorderflowlist的status=1
            //3.分配时间设为0
            msg = "";
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                orderInfo curOi = dataBase.orderInfo.FirstOrDefault(o => o.OrderProductId == taskInfo.OrderProductId);
                if (curOi == null)
                {
                    msg = "没有找到该产品，请检查或是重启程序！";
                }
                else
                {
                    if (!curOi.WorkOrderFlowList.IsLoaded)
                    {
                        curOi.WorkOrderFlowList.Load();
                    }
                    WorkOrderFlowList wfl = curOi.WorkOrderFlowList.ToList().First(wf => wf.Status == (int)OrderFlowListStatus.UseableAccept || wf.Status == (int)OrderFlowListStatus.Useable);
                    if (wfl == null)
                    {
                        msg = "找不到当前可用的结点，请检查或是重启程序！";
                    }
                    else
                    {
                        wfl.Status = (int)OrderFlowListStatus.Useable;
                        wfl.UserId = 0;
                    }
                }

                try
                {
                    dataBase.SaveChanges();
                }
                catch (Exception ex)
                {
                    msg = "退回时出错," + ex.Message;
                }

            }
            if (string.IsNullOrEmpty(msg))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool OldCompleteDesinedWork(TaskInfo taskInfo, int Uid, List<BigPicInfo> _ImportPicList, bool isOriPicOver,List<EPByPhotoSpecInfo> epByPhotoSpecInfoList,WorkShop_Info workshop)
        {
            try
            {
                if (!isOriPicOver)
                {
                    using (TransactionScope trs = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 5, 0)))
                    {
                        try
                        {
                            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
                            {
                                //修改产品的备注

                                //从photoInfo表中删除旧图片
                                paperFace oldPaperFace;
                                paperType oldPaperType;
                                GetOldFaceAndType(out oldPaperFace, out oldPaperType, taskInfo.OrderProductId, DataEntites);
                                photoInfo oldPhotoInfo = _dal.DeletePhotoByOrderProductId(taskInfo.OrderProductId, DataEntites);
                                //string strPathDir = oldPhotoInfo.picPath.Substring(0, oldPhotoInfo.picPath.LastIndexOf(@"\"));
                                //_CurrentDirPath = strPathDir.Substring(0, strPathDir.LastIndexOf(@"\"));
                                _CurrentDirPath = oldPhotoInfo.picPath.Substring(0, oldPhotoInfo.picPath.LastIndexOf(@"\"));
                                //移动图片
                                string newDirPath = _CurrentDirPath + "\\PSD\\";
                                string newDirPathBackUp = newDirPath + "\\backup\\";
                                if (!Directory.Exists(newDirPath))
                                {
                                    Directory.CreateDirectory(newDirPath);
                                }
                                if (!Directory.Exists(newDirPathBackUp))
                                {
                                    Directory.CreateDirectory(newDirPathBackUp);
                                }
                                foreach (var item in _ImportPicList)
                                {
                                    FileInfo fi = new FileInfo(item.PicPath);
                                    fi.CopyTo(newDirPath + item.PicName, true);

                                    //将设计好的也备份一次
                                    fi.CopyTo(newDirPathBackUp + item.PicName, true);
                                }
                                string strOldRemark;
                                if (oldPhotoInfo.Remark.EndsWith("\\"))
                                {
                                    strOldRemark = oldPhotoInfo.Remark.Substring(0, oldPhotoInfo.Remark.LastIndexOf("\\"));
                                }
                                else
                                {
                                    strOldRemark = oldPhotoInfo.Remark;
                                }

                                List<photoInfo> newPigPhotoList = new List<photoInfo>();
                                foreach (var item in _ImportPicList)
                                {
                                    //for (int i = 0; i < item.NUM; i++)//一底多张的情况
                                    //{
                                        photoInfo pi = new photoInfo();
                                        //pi.photoName = i != 0 ? item.PicName + "(" + i + ")" : item.PicName;
                                        pi.photoName =  item.PicName;
                                        pi.picPath = newDirPath + item.PicName;//还是指向的同一张照片
                                        pi.pixHeight = item.PixHeight;
                                        pi.pixWidth = item.PixWidth;
                                        pi.Remark = strOldRemark + item.PicName;
                                        pi.status = Convert.ToInt32(PhotoStatus.NoDistributePrinter);
                                        pi.Width = item.Width;
                                        pi.Height = item.Height;
                                        //pi.TotalNum = oldPhotoInfo.TotalNum;
                                        pi.TotalNum = item.NUM;
                                        pi.IsModifySize = oldPhotoInfo.IsModifySize;

                                        pi.paperType = oldPaperType;
                                        pi.paperFace = oldPaperFace;

                                        pi.OldPicPath = " ";
                                        pi.PhotoBarCode = " ";
                                        pi.printerId = oldPhotoInfo.printerId;
                                        newPigPhotoList.Add(pi);
                                    //}

                                }
                                //DesignCommint dm = new DesignCommint();
                                //dm.commintDouble = 0;
                                //dm.commintSingle = 0;
                                //dm.commintNum = newPigPhotoList.Count;
                                //dm.orderproductid = taskInfo.OrderProductId;
                                //DataEntites.AddToDesignCommint(dm);
                                //向数据表添加新图片的记录                               
                                _dal.AddNewPic(newPigPhotoList, taskInfo, DataEntites);
                            }

                            trs.Complete();
                        }
                        catch (Exception ex)
                        {
                            WriteLogForCheck.WriteLogFile("在进行设计提交时，旧照片删除，新照片添加时出错:" + ex.Message);
                            return false;
                        };
                    }

                    return CompleteWork(taskInfo.TechId, Uid, taskInfo.OrderProductId,epByPhotoSpecInfoList,workshop);
                }
                else//原片导入
                {
                    //原片导入时读取照片的尺寸信息写入到photoinfo中

                    return CompleteWork(taskInfo.TechId, Uid, taskInfo.OrderProductId,epByPhotoSpecInfoList,workshop);
                }
            }
            catch (Exception ex)
            {
                throw ex;
                //return false;
            }
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="taskInfo"></param>
        /// <param name="Uid"></param>
        /// <param name="_ImportPicList"></param>
        /// <param name="isOriPicOver"></param>
        /// <param name="epByPhotoSpecInfoList"></param>
        /// <param name="workshop"></param>
        /// <returns></returns>
        public bool CompleteDesinedWork(TaskInfo taskInfo, int Uid, List<BigPicInfo> _ImportPicList, bool isOriPicOver, List<EPByPhotoSpecInfo> epByPhotoSpecInfoList, WorkShop_Info workshop)
        {
            System.Data.Common.DbTransaction tran =null;
            try
            {
                if (!isOriPicOver)
                {
         
                        try
                        {
                            using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
                            {
                                if (DataEntites.Connection.State != System.Data.ConnectionState.Open)
                                {
                                    try
                                    {
                                        DataEntites.Connection.Open();
                      
                                    }
                                    catch (Exception ex)
                                    {
                                        WriteLogForCheck.WriteLogFile(ex.Message);
                                    }
                                }
                                using (tran = DataEntites.Connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                                {

                                    //修改产品的备注

                                    //从photoInfo表中删除旧图片
                                    paperFace oldPaperFace;
                                    paperType oldPaperType;
                                    GetOldFaceAndType(out oldPaperFace, out oldPaperType, taskInfo.OrderProductId, DataEntites);
                                    photoInfo oldPhotoInfo = _dal.DeletePhotoByOrderProductId(taskInfo.OrderProductId, DataEntites);
                                    //string strPathDir = oldPhotoInfo.picPath.Substring(0, oldPhotoInfo.picPath.LastIndexOf(@"\"));
                                    //_CurrentDirPath = strPathDir.Substring(0, strPathDir.LastIndexOf(@"\"));
                                    _CurrentDirPath = oldPhotoInfo.picPath.Substring(0, oldPhotoInfo.picPath.LastIndexOf(@"\"));
                                    //移动图片
                                    string newDirPath = _CurrentDirPath + "\\PSD\\";
                                    string newDirPathBackUp = newDirPath + "\\backup\\";
                                    if (!Directory.Exists(newDirPath))
                                    {
                                        Directory.CreateDirectory(newDirPath);
                                    }
                                    if (!Directory.Exists(newDirPathBackUp))
                                    {
                                        Directory.CreateDirectory(newDirPathBackUp);
                                    }
                                    foreach (var item in _ImportPicList)
                                    {
                                        FileInfo fi = new FileInfo(item.PicPath);
                                        fi.CopyTo(newDirPath + item.PicName, true);

                                        //将设计好的也备份一次
                                        fi.CopyTo(newDirPathBackUp + item.PicName, true);
                                    }
                                    string strOldRemark;
                                    if (oldPhotoInfo.Remark.EndsWith("\\"))
                                    {
                                        strOldRemark = oldPhotoInfo.Remark.Substring(0, oldPhotoInfo.Remark.LastIndexOf("\\"));
                                    }
                                    else
                                    {
                                        strOldRemark = oldPhotoInfo.Remark;
                                    }

                                    List<photoInfo> newPigPhotoList = new List<photoInfo>();
                                    foreach (var item in _ImportPicList)
                                    {
                                        //for (int i = 0; i < item.NUM; i++)//一底多张的情况
                                        //{
                                        photoInfo pi = new photoInfo();
                                        //pi.photoName = i != 0 ? item.PicName + "(" + i + ")" : item.PicName;
                                        pi.photoName = item.PicName;
                                        pi.picPath = newDirPath + item.PicName;//还是指向的同一张照片
                                        pi.pixHeight = item.PixHeight;
                                        pi.pixWidth = item.PixWidth;
                                        pi.Remark = strOldRemark + item.PicName;
                                        pi.status = Convert.ToInt32(PhotoStatus.NoDistributePrinter);
                                        pi.Width = item.Width;
                                        pi.Height = item.Height;
                                        //pi.TotalNum = oldPhotoInfo.TotalNum;
                                        pi.TotalNum = item.NUM;
                                        pi.IsModifySize = oldPhotoInfo.IsModifySize;

                                        pi.paperType = oldPaperType;
                                        pi.paperFace = oldPaperFace;

                                        pi.OldPicPath = " ";
                                        pi.PhotoBarCode = " ";
                                        pi.printerId = oldPhotoInfo.printerId;
                                        newPigPhotoList.Add(pi);
                                        //}

                                    }
                                    //DesignCommint dm = new DesignCommint();
                                    //dm.commintDouble = 0;
                                    //dm.commintSingle = 0;
                                    //dm.commintNum = newPigPhotoList.Count;
                                    //dm.orderproductid = taskInfo.OrderProductId;
                                    //DataEntites.AddToDesignCommint(dm);
                                    //向数据表添加新图片的记录                               
                                    _dal.AddNewPic(newPigPhotoList, taskInfo, DataEntites);
                                    tran.Commit();
                                }
                   
                            }
                        }
                    
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            WriteLogForCheck.WriteLogFile("在进行设计提交时，旧照片删除，新照片添加时出错:" + ex.Message);
                            
                            return false;
                        };
                    
            
                    return CompleteWork(taskInfo.TechId, Uid, taskInfo.OrderProductId, epByPhotoSpecInfoList, workshop);
                }
                else//原片导入
                {
                    //原片导入时读取照片的尺寸信息写入到photoinfo中

                    return CompleteWork(taskInfo.TechId, Uid, taskInfo.OrderProductId, epByPhotoSpecInfoList, workshop);
                }
            }
            catch (Exception ex)
            {
                tran.Rollback();
                throw ex;
                //return false;
            }
            return true;
        }

       

        public bool ReBackTask(TaskInfo taskInfo, out string strMsg, int rebackType)
        {
            strMsg = string.Empty;
            if (rebackType == 0)//退回给组长
            {
                return ReBackTask(taskInfo, out strMsg);
            }
            else//退回给上一节点
            {
                //1、检查是否有一节点，并且上一节点不能为开始
                //2、将当前结点的userid=0\status=0
                //3、让上一节点的status=0
                //4、修改orderInfo的Remark
                using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
                {
                    orderInfo curOi = dataBase.orderInfo.FirstOrDefault(o => o.OrderProductId == taskInfo.OrderProductId);
                    if (curOi == null)
                    {
                        strMsg = "没有找到该产品，请检查或是重启程序！";
                        return false;
                    }

                    if (!curOi.WorkOrderFlowList.IsLoaded)
                    {
                        curOi.WorkOrderFlowList.Load();
                    }
                    WorkOrderFlowList curWfl = curOi.WorkOrderFlowList.ToList().FirstOrDefault(wf => wf.Status == (int)OrderFlowListStatus.UseableAccept || wf.Status == (int)OrderFlowListStatus.Useable);
                    if (curWfl == null)
                    {
                        strMsg = "找不到当前可用的结点，请检查或是重启程序！";
                        return false;
                    }
                    else
                    {
                        //上一个节点
                        List<WorkOrderFlowList> preWflList = curOi.WorkOrderFlowList.ToList().Where(w => w.WorkOrder < curWfl.WorkOrder).OrderByDescending(w => w.WorkOrder).ToList();

                        if (preWflList.Count < 2)
                        {
                            strMsg = "这是第一个节点，没有上一节点，请检查！";
                            return false;
                        }


                        WorkOrderFlowList preWfl = preWflList.FirstOrDefault();
                        if (preWfl.WorkOrder == 1)
                        {
                            strMsg = "不能退回到开始节点，请重新选择！";
                            return false;
                        }
                        curOi.Remark = taskInfo.ProductRemark;
                        preWfl.Status = (int)OrderFlowListStatus.Useable;

                        curWfl.Status = (int)OrderFlowListStatus.Wait;
                        curWfl.UserId = 0;
                    }

                    try
                    {
                        dataBase.SaveChanges();
                        return true;
                    }
                    catch (Exception ex)
                    {
                        strMsg = "在保存数据库时出错," + ex.Message;
                        return false;
                    }
                }
            }
        }

        /// <summary>
        /// 提交时如果需要裁剪的图片需要向数据库更新图片的尺寸,同时修改产品的面积，和业绩统计里面的面积
        /// </summary>
        /// <param name="needModifySizePs"></param>
        public void ModifyPhotoSize(List<PhotoInfo_GM> needModifySizePs)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                photoInfo pd = null;
                foreach (var pi in needModifySizePs)
                {
                    pd = db.photoInfo.FirstOrDefault(p => p.photoId == pi.PhotoId);
                    if (pd != null)
                    {
                        pd.pixHeight = pi.PixHeight;
                        pd.pixWidth = pi.PixWidth;
                        pd.Width = pi.Width;
                        pd.Height = pi.Height;
                    }
                }

                db.SaveChanges();
                //如果orderInfo的ProductType是需要设计类的产品，则不需要更新面积和业绩，如果是不需要设计的则需要回写

                if (pd != null)
                {
                    pd.orderInfoReference.Load();
                    //不需要设计的直出或是产品都要更新面积和相应的业绩
                    if (pd.orderInfo.ProductType == (int)OrderInfoProductType.NoNeedDesignPrint || pd.orderInfo.ProductType == (int)OrderInfoProductType.NoNeedDesignProduct)
                    {
                        double totoalArea = 0;
                        pd.orderInfo.photoInfo.Load();

                        totoalArea = pd.orderInfo.photoInfo.Sum(p => p.Width * p.Height * 2.54 * 2.54 / 10000 * (p.TotalNum ?? 1)) * pd.orderInfo.productNum;
                        pd.orderInfo.Area = totoalArea;

                        //修改相应的业绩

                        foreach (var en in db.New_EmployeePerformance.Where(e => e.OrderproductId == pd.orderInfo.OrderProductId))
                        {
                            en.PreOrderAreas = totoalArea;
                            en.OrderArea = totoalArea;
                        }
                        db.SaveChanges();
                    }
                }
            }
        }
        /// <summary>
        /// 获取该客人需要设计的产品名称
        /// </summary>
        /// <param name="inCtmName"></param>
        /// <returns></returns>
        public List<TaskInfo> GetCtmProduct(string inCtmName)
        {
            List<TaskInfo> taskInfoList = new List<TaskInfo>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<orderInfo> orderInfoList = db.orderInfo.Where(order => (order.WorkOrderFlowList.FirstOrDefault(wf => wf.tb_Tech.IsDesign == true && wf.Status == 1)) != null && order.CtmName == inCtmName).ToList();
                foreach (orderInfo oi in orderInfoList)
                {
                    TaskInfo taskInfo = new TaskInfo();
                    taskInfo.PhotoList = new List<PhotoInfo_GM>();
                    if (!oi.photoInfo.IsLoaded)
                    {
                        oi.photoInfo.Load();
                    }
                    foreach (var item in oi.photoInfo)
                    {
                        PhotoInfo_GM pi = new PhotoInfo_GM()
                        {
                            PhotoId = item.photoId,
                            PicPath = item.picPath,
                            PhotoName =item.photoName
                        };
                        taskInfo.PhotoList.Add(pi);
                        
                    }
                    taskInfo.OrderProductName = oi.OrderProductName;
                    taskInfo.OrderProductId = oi.OrderProductId;
                    taskInfoList.Add(taskInfo);
                }
            }
            return taskInfoList;
        }

        /// <summary>
        /// 获取按照片规格统计名称列表
        /// </summary>
        /// <returns></returns>
        public List<EPByPhotoSpecInfo> GetEPByPhotoSpecInfoList()
        {
            List<EPByPhotoSpecInfo> list = new List<EPByPhotoSpecInfo>();
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    List<New_EmployeePerformance_SpecInfo> epList = db.New_EmployeePerformance_SpecInfo.ToList();
                    foreach (var item in epList)
                    {
                        EPByPhotoSpecInfo epByphotoSpecInfo = new EPByPhotoSpecInfo()
                        {
                            MaxArea = item.MaxArea,
                            MinArea = item.MinArea,
                            SpecId = item.SpecId,
                            SpecName = item.SpecName
                        };
                        list.Add(epByphotoSpecInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }


        /// <summary>
        /// 获得车间信息
        /// </summary>
        /// <returns></returns>
        public WorkShop_Info GetWorkShopInfo()
        {
            WorkShop_Info wsInfo = null;
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    WorkShop ws = db.WorkShop.FirstOrDefault();
                    if (ws != null)
                    {
                        wsInfo = new WorkShop_Info()
                        {
                            Address = ws.Address,
                            AutoAssignShop = ws.AutoAssignShop,
                            CustomerTel = ws.CustomerTel,
                            Email = ws.Email,
                            FinanceTel = ws.FinanceTel,
                            QQ = ws.QQ,
                            Remark = ws.Remark,
                            WorkShopName = ws.WorkShopName,
                            InsertEPByPhotoSpec = ws.InsertEmployeePerfermanceByPhotoSpec,
                            ControlNonexistenceTechByPriority = ws.ControlNonexistenceTechByPriority
                        };
                    }
                }
            }
            catch
            {

            }
            return wsInfo;
        }


        /// <summary>
        /// 获得员工业绩
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="dtStart"></param>
        /// <param name="dtEnd"></param>
        /// <returns></returns>
        public List<New_EmployeePerformanceBySpec_Info> GetEPByPhotoSpec(string userName, DateTime dtStart, DateTime dtEnd)
        {
            List<New_EmployeePerformanceBySpec_Info> epList = new List<New_EmployeePerformanceBySpec_Info>();
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    List<New_EmployeePerformanceBySpec> dbepList = db.New_EmployeePerformanceBySpec.Where(e=>e.UserName ==userName&&e.CompleteDateTime>=dtStart&&e.CompleteDateTime <=dtEnd).ToList();
                    foreach (var item in dbepList)
                    {
                        if (!item.New_EmployeePerformanceBySpecPhoto.IsLoaded)
                        {
                            item.New_EmployeePerformanceBySpecPhoto.Load();
                        }
                        New_EmployeePerformanceBySpec_Info epInfo = new New_EmployeePerformanceBySpec_Info()
                        {
                            CompleteDateTime = item.CompleteDateTime,
                            Id = item.Id,
                            OrderEditTime = item.OrderEditTime,
                            orderProductId = item.orderProductId,
                            orderProductName = item.orderProductName,
                            PageNum = item.PageNum,
                            ShopName = item.ShopName,
                            SpecName = item.SpecName,
                            Status = item.Status,
                            TechName = item.TechName,
                            UserId = item.UserId,
                            UserName = item.UserName,
                            epPhotoInfoList = new List<New_EmployeePerformanceBySpecPhoto_Info>()
                        };
                        foreach (var epphoto in item.New_EmployeePerformanceBySpecPhoto)
                        {

                            New_EmployeePerformanceBySpecPhoto_Info epPhotoInfo = new New_EmployeePerformanceBySpecPhoto_Info()
                            {
                                Area = epphoto.Area,
                                EmployeePerformanceBySpecId = epphoto.New_EmployeePerformanceBySpec.Id,
                                Height = epphoto.Height,
                                Num = epphoto.Num,
                                photoId = epphoto.photoId,
                                PhotoName = epphoto.PhotoName,
                                Width = epphoto.Width,
                            };
                            epInfo.epPhotoInfoList.Add(epPhotoInfo);
                        }
                        epList.Add(epInfo);
                    }
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }

            return epList;
        }
        public List<New_EmployeePerformanceBySpec_Info> GetEPByPhotoSpecGroup(string userName, DateTime dtStart, DateTime dtEnd)
        {
            List<New_EmployeePerformanceBySpec_Info> epList = new List<New_EmployeePerformanceBySpec_Info>();
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    users user = db.users.FirstOrDefault(u => u.UserName == userName);
                    user.tb_WorkerGroupReference.Load();
                    List<users> listUser = db.users.Where(u => u.tb_WorkerGroup.GroupId == user.tb_WorkerGroup.GroupId && u.IsUseful).ToList();
                    foreach (users u in listUser)
                    {
                        List<New_EmployeePerformanceBySpec> dbepList = db.New_EmployeePerformanceBySpec.Where(e => e.UserId == u.userID && e.CompleteDateTime >= dtStart && e.CompleteDateTime <= dtEnd).ToList();
                        foreach (var item in dbepList)
                        {
                            if (!item.New_EmployeePerformanceBySpecPhoto.IsLoaded)
                            {
                                item.New_EmployeePerformanceBySpecPhoto.Load();
                            }
                            New_EmployeePerformanceBySpec_Info epInfo = new New_EmployeePerformanceBySpec_Info()
                            {
                                CompleteDateTime = item.CompleteDateTime,
                                Id = item.Id,
                                OrderEditTime = item.OrderEditTime,
                                orderProductId = item.orderProductId,
                                orderProductName = item.orderProductName,
                                PageNum = item.PageNum,
                                ShopName = item.ShopName,
                                SpecName = item.SpecName,
                                Status = item.Status,
                                TechName = item.TechName,
                                UserId = item.UserId,
                                UserName = item.UserName,
                                epPhotoInfoList = new List<New_EmployeePerformanceBySpecPhoto_Info>()
                            };
                            foreach (var epphoto in item.New_EmployeePerformanceBySpecPhoto)
                            {

                                New_EmployeePerformanceBySpecPhoto_Info epPhotoInfo = new New_EmployeePerformanceBySpecPhoto_Info()
                                {
                                    Area = epphoto.Area,
                                    EmployeePerformanceBySpecId = epphoto.New_EmployeePerformanceBySpec.Id,
                                    Height = epphoto.Height,
                                    Num = epphoto.Num,
                                    photoId = epphoto.photoId,
                                    PhotoName = epphoto.PhotoName,
                                    Width = epphoto.Width,
                                };
                                epInfo.epPhotoInfoList.Add(epPhotoInfo);
                            }
                            epList.Add(epInfo);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return epList;
        }
        /// <summary>
        /// 修改产品备注 
        /// </summary>
        /// <param name="remark"></param>
        public void UpdateOrderProductRemark(string remark,int orderproductId)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                orderInfo oi = db.orderInfo.FirstOrDefault(o=>o.OrderProductId ==orderproductId);
                oi.Remark = remark;
                db.SaveChanges();
            }
        }


        /// <summary>
        /// 检查实际照片与模版设置尺寸数量是否一致
        /// </summary>
        /// <param name="taskInfo"></param>
        /// <param name="bigPicInfoList"></param>
        /// <param name="retMessage"></param>
        /// <returns></returns>
        public bool CheckProductPhotoSize(TaskInfo taskInfo, List<BigPicInfo> bigPicInfoList,out string retMessage)
        {
            retMessage = "";
            bool ret = false;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                orderInfo oi = db.orderInfo.FirstOrDefault(o=>o.OrderProductId ==taskInfo.OrderProductId);
                if (oi != null)
                {
                    if (!oi.Tb_ProductReference.IsLoaded)
                    {
                        oi.Tb_ProductReference.Load();
                    }
                    if (!oi.Tb_Product.Photo_Size.IsLoaded)
                    {
                        oi.Tb_Product.Photo_Size.Load();
                    }
                    if (oi.Tb_Product.Photo_Size.Count > 0)//产品有设置检查尺寸
                    {
                        List<PhotoSize_Info> photoSizeInfoList = ConvertToModel(oi.Tb_Product.Photo_Size.ToList());
                        foreach (var bigPic in bigPicInfoList)//尺寸检查
                        {
                            if (photoSizeInfoList.Exists(p=>p.PhotoSize ==bigPic.PhotoSize))//如果要导入的照片的尺寸包含在模版尺寸之中，则该照片通过尺寸检查
                            {
                                bigPic.IsMatchSize =true;
                            }
                            else
                            {
                                bigPic.IsMatchSize = false;
                            }
                        }
                        if (bigPicInfoList.Where(p => p.IsMatchSize == false).ToList().Count > 0)//是否存在尺寸不对的照片
                        {
                            ret = false;
                            retMessage = "有照片尺寸与设定的尺寸不一致！";
                        }
                        else
                        {
                            foreach (var item in bigPicInfoList.GroupBy(p => p.PhotoSize))//检查每个尺寸的页数是否和设置的一致
                            {
                                int pageNum =photoSizeInfoList.First(p => p.PhotoSize == item.Key).PageNum;
                                if (item.Count() != pageNum)
                                {
                                    ret = false;
                                    retMessage = "照片尺寸宽(英寸)：" + item.First().Width + ",高(英寸)" + item.First().Height + "的页数和设定的不一致！实际页数：" + item.Count() + ",设定页数：" + pageNum;
                                    break;
                                }
                                else
                                {
                                    ret = true;
                                }
                            }
                        }
                    }
                    else//产品没有设置检查尺寸,直接通过尺寸检查
                    {
                        ret = true;
                    }
                }
                else
                {
                    ret = false;
                    retMessage = "产品id:"+taskInfo.OrderProductId+"不存在于数据库中！";
                }
            }

            return ret;
        }

        /// <summary>
        /// 转换实体
        /// </summary>
        /// <param name="photoSizeList"></param>
        /// <returns></returns>
        private List<PhotoSize_Info> ConvertToModel(List<Photo_Size> photoSizeList)
        {
            List<PhotoSize_Info> photoSizeInfoList = new List<PhotoSize_Info>();
            foreach (var item in photoSizeList)
            {
                PhotoSize_Info psInfo = new PhotoSize_Info()
                {
                    Describe = item.Describe,
                    HeightMAX = item.HeightMAX,
                    HeightMIN = item.HeightMIN,
                    PageNum = item.PageNum,
                    SizeId = item.SizeId,
                    WidthMAX = item.WidthMAX,
                    WidthMIN = item.WidthMIN
                };
                photoSizeInfoList.Add(psInfo);
            }
            return photoSizeInfoList;
        }

        /// <summary>
        /// 暂停产品
        /// </summary>
        /// <param name="orderProductId">产品编号</param>
        /// <param name="status">0表示暂停，1表示恢复</param>
        /// <param name="remark">备注</param>
        /// <param name="userId">用户ID</param>
        public void PauseOrderProduct(int orderProductId, int status, string remark, int userId)
        {

            System.Transactions.TransactionOptions options = new System.Transactions.TransactionOptions();
            options.Timeout = new TimeSpan(0, 0, 600);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;

            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {


                if (db.Connection.State != System.Data.ConnectionState.Open)
                {
                    db.Connection.Open();
                }


                using (System.Data.Common.DbTransaction tran = db.Connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                {
                    try
                    {
                        orderInfo info = db.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductId);
                        if (!info.Tb_OrderBagReference.IsLoaded)
                        {
                            info.Tb_OrderBagReference.Load();
                        }
                        if (!info.WorkOrderFlowList.IsLoaded)
                        {
                            info.WorkOrderFlowList.Load();
                        }
                        WorkOrderFlowList wfi = info.WorkOrderFlowList.FirstOrDefault(w => w.Status == 1);
                        if (wfi == null)
                        {
                            return;
                        }

                        if (!wfi.tb_TechReference.IsLoaded)
                        {
                            wfi.tb_TechReference.Load();
                        }


                        tb_Tech tech = wfi.tb_Tech;
                        if (tech == null)
                            return;

                        List<New_EmployeePerformance> listNEP = db.New_EmployeePerformance.Where(e => e.OrderproductId == info.OrderProductId).ToList();
                        int statusAble = (int)COM.OrderFlowListStatus.Useable;
                        int statusStop = (int)COM.OrderFlowListStatus.UnProduct;
                        if (status == 0)                           //停止
                        {
                            wfi.Status = statusStop;
                            info.Tb_OrderBag.Status = (int)OrderBagStatus.ProductStop;
                            info.status = (int)COM.OrderInfoStatus.Stop;
                            listNEP.ForEach(p => p.Status = (int)COM.OrderInfoStatus.Stop);//修改人员业绩状态
                        }
                        else                                        //恢复
                        {
                            wfi.Status = statusAble;
                            info.Tb_OrderBag.Status = (int)OrderBagStatus.Doing;
                            info.status = (int)OrderInfoStatus.Doing;
                            listNEP.ForEach(p => p.Status = (int)COM.OrderInfoStatus.Doing);//修改人员业绩状态
                        }


                        //停止(恢复)记录
                        CtmOperateRecord newRecord = new CtmOperateRecord();
                        newRecord.CreateTime = DateTime.Now;
                        newRecord.OperateType = status;
                        newRecord.orderInfo = info;
                        newRecord.Remark = remark;
                        newRecord.tb_Tech = tech;
                        newRecord.users = db.users.FirstOrDefault(u => u.userID == userId);
                        db.AddToCtmOperateRecord(newRecord);

                        db.SaveChanges();

                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        throw ex;
                    }
                }
            }


        }
    }
}
